﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Derrick.Web
{
    public class WebSocketResponse : Response
    {

        public String ComputeWebSocketHandshakeSecurityHash09(string secWebSocketKey)
        {
            const String magicKey = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            String secWebSocketAccept = String.Empty;

            Trace.WriteLineIf(_traceSwitch.TraceVerbose, "WebSocketResponse::ComputeWebSocketHandshakeSecurityHash09()...", "Web Socket Service");

            String ret = secWebSocketKey + magicKey;
            SHA1 sha = new SHA1CryptoServiceProvider();
            byte[] sha1Hash = sha.ComputeHash(Encoding.UTF8.GetBytes(ret));
            secWebSocketAccept = Convert.ToBase64String(sha1Hash);
            return secWebSocketAccept;
        }

        public void SendHandshakeResponse(System.Net.Sockets.NetworkStream stream, WebSocketClient client)
        {
            _traceSwitch = new TraceSwitch("TraceLevelSwitch", "COMET Client.");
            Trace.WriteLineIf(_traceSwitch.TraceVerbose, "WebSocketResponse::SendHandshakeResponse()...Sending handshake response to confirm connection.", "Web Socket Service");

            if (File != null && !File.Exists)
            {
                return;
            }

            //string webSocketKeyString = ConfigurationManager.AppSettings["Sec-WebSocket-Accept"];
            string webSocketKeyString = ComputeWebSocketHandshakeSecurityHash09(client.WebSocketKey);
            string webSocketProtocol = ConfigurationManager.AppSettings["Sec-WebSocket-Protocol"];

            AddHeader("Upgrade", "websocket");
            AddHeader("Connection", "Upgrade");
            AddHeader("Sec-WebSocket-Accept", webSocketKeyString);
            AddHeader("Sec-WebSocket-Protocol", webSocketProtocol);

            StringBuilder r = new StringBuilder();

            try
            {

                r.Append("HTTP/1.1 101 Switching Protocols\r\n");

                foreach (KeyValuePair<string, string> header in Headers)
                {
                    r.Append(header.Key + ": " + header.Value + "\r\n");
                }

                r.Append("\r\n");

                byte[] htext = Encoding.ASCII.GetBytes(r.ToString());
                stream.Write(htext, 0, htext.Length);

                Trace.WriteLineIf(_traceSwitch.TraceVerbose, "WebSocketResponse::SendHandshakeResponse()...Sent successfully.", "Web Socket Service");

            }
            catch (Exception ex)
            {
                Trace.WriteLine("Exception thrown when sending response: " + ex.ToString());
                Trace.Flush();
            }


        }

        public void SendMessage(string message, WebSocketClient client)
        {
            client.Send(message);
        }

        public static WebSocketResponse GetWebSocketResponse(string message)
        {
            WebSocketResponse res = new WebSocketResponse();
            //res.Body = html;
            res.Body = message;
            return res;
        }
    }
}
